package com.njit.office.service.impl;

import com.njit.office.dao.LoginUserMapper;
import com.njit.office.dao.TeamMapper;
import com.njit.office.dao.UserMapper;
import com.njit.office.dao.UserTeamsMapper;
import com.njit.office.dataobject.LoginUser;
import com.njit.office.dataobject.Team;
import com.njit.office.dataobject.User;
import com.njit.office.dataobject.UserTeams;
import com.njit.office.model.Result;
import com.njit.office.model.TeamModel;
import com.njit.office.service.TeamService;
import com.njit.office.utils.IDUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Team服务的实现类
 */
@Service("TeamService")
public class TeamServiceImpl implements TeamService {

    @Resource
    TeamMapper teamMapper;

    @Resource
    UserTeamsMapper userTeamsMapper;

    @Resource
    LoginUserMapper loginUserMapper;

    @Override
    public Result getAllMembers(String teamId) {

        Result result = new Result();

        List<UserTeams> userTeams = userTeamsMapper.selectByTeamId(teamId);
        List<LoginUser> loginUsers = new ArrayList<>();
        for (UserTeams userTeams1 : userTeams) {
            LoginUser loginUser = loginUserMapper.selectByPrimaryKey(userTeams1.getUserId());
            loginUsers.add(loginUser);
        }
        result.setSuccess(true);
        result.setData(loginUsers);
        return result;
    }

    @Override
    public Result createTeam(String userId, String teamName) {

        Result result = new Result();
        //判断userId是否存在
        if (!userIsExist(userId)) {
            result.setSuccess(false);
            result.setErrCode("21");
            result.setErrMsg("用户未找到");
            return result;
        }

        //查看team的名字是否存在
        Team team = teamMapper.selectByTeamName(teamName);
        if (team != null && team.getId() != null) {
            result.setSuccess(false);
            result.setErrCode("15");
            result.setErrMsg("team名称已经存在");
            return result;
        }


        //保证邀请码不重复
        String inviteCode = "";
        while (true) {
            //生成邀请码
            inviteCode = IDUtils.toInviteCode();
            //查看邀请码是否存在
            Team team1 = teamMapper.selectByInviteCode(inviteCode);
            if (team1 == null) {
                break;
            }
        }
        //数据库操作
        try {
            //组建team对象
            String teamId = IDUtils.toUUID();
            Team newTeam = new Team();
            newTeam.setId(teamId);
            newTeam.setName(teamName);
            newTeam.setState(true);
            newTeam.setGmtCreated(new Date());
            newTeam.setGmtModified(new Date());
            newTeam.setInviteCode(inviteCode);
            teamMapper.insert(newTeam);

            //创建者加入team
            UserTeams userTeams = new UserTeams();
            userTeams.setId(IDUtils.toUUID());
            userTeams.setTeamId(teamId);
            userTeams.setUserId(userId);
            userTeams.setJoinTime(new Date());
            userTeams.setIsCreator(true);
            userTeamsMapper.insert(userTeams);

            //人数+1
            teamMapper.updateMemberNumByPriamryKey(teamId, 1);
        } catch (Exception e) {
            e.printStackTrace();
            result.setSuccess(false);
            result.setErrCode("16");
            result.setErrMsg("创建team失败");
            return result;
        }
        result.setSuccess(true);
        return result;
    }

    @Override
    public Result joinTeam(String userId, String inviteCode) {
        Result result = new Result();
        //判断userId是否存在
        if (!userIsExist(userId)) {
            result.setSuccess(false);
            result.setErrMsg("用户未找到");
            return result;
        }
        //判断invitecode是否存在
        Team team = teamMapper.selectByInviteCode(inviteCode);
        if (team == null) {
            result.setSuccess(false);
            result.setErrMsg("邀请码不存在");
            return result;
        }

        //判断是否加入过
        UserTeams userTeams = userTeamsMapper.selectByTeamIdAndUserId(team.getId(), userId);
        if (userTeams != null) {
            result.setSuccess(false);
            result.setErrMsg("用户已经在team中");
            return result;
        }

        userTeams = new UserTeams();
        userTeams.setId(IDUtils.toUUID());
        userTeams.setIsCreator(false);
        userTeams.setJoinTime(new Date());
        userTeams.setTeamId(team.getId());
        userTeams.setUserId(userId);
        userTeamsMapper.insert(userTeams);

        //更新小组人数
        int i = 1 + team.getMemberNum();
        teamMapper.updateMemberNumByPriamryKey(team.getId(), i);
        result.setSuccess(true);
        return result;
    }

    @Override
    public Result dismissTeam(String userId, String teamId) {

        Result result = new Result();

        //判断userId是否存在
        if (!userIsExist(userId)) {
            result.setSuccess(false);
            result.setErrCode("21");
            result.setErrMsg("用户未找到");
            return result;
        }
        //判断是不是创建者
        UserTeams userTeams = userTeamsMapper.selectByTeamIdAndUserId(teamId, userId);
        if (!userTeams.getIsCreator()) {
            result.setSuccess(false);
            result.setErrCode("23");
            result.setErrMsg("只有team创建者才有权限解散team");
            return result;
        }

        //判断team是否存在
        Team team = teamMapper.selectByPrimaryKey(teamId);
        if (team == null) {
            result.setSuccess(false);
            result.setErrCode("19");
            result.setErrMsg("要解散的team不存在");
            return result;
        }


        //解散team
        try {
            teamMapper.deleteByPrimaryKey(team.getId());
            //删除加入成员记录
            userTeamsMapper.deleteByTeamId(team.getId());
        } catch (Exception e) {
            e.printStackTrace();
            result.setSuccess(false);
            result.setErrCode("20");
            result.setErrMsg("解散team失败");
            return result;
        }
        result.setSuccess(true);

        return result;
    }

    @Override
    public Result getCreatedTeams(String userId) {
        Result result = new Result();

        //判断userId是否存在
        if (!userIsExist(userId)) {
            result.setSuccess(false);
            result.setErrMsg("用户未找到");
            return result;
        }

        List<TeamModel> resultTeams = new ArrayList<>();

        List<UserTeams> userTeams = userTeamsMapper.selectByUserId(userId);

        for (UserTeams userTeam : userTeams) {
            if (!userTeam.getIsCreator()) {
                continue;
            }
            Team team = teamMapper.selectByPrimaryKey(userTeam.getTeamId());

            TeamModel teamModel = new TeamModel();
            teamModel.setTeamId(userTeam.getTeamId());
            teamModel.setName(team.getName());
            teamModel.setMemberNum(team.getMemberNum());
            teamModel.setInviteCode(team.getInviteCode());
            teamModel.setCreateTime(team.getGmtCreated());

            resultTeams.add(teamModel);
        }
        result.setSuccess(true);
        result.setData(resultTeams);
        return result;
    }

    @Override
    public Result getJoinedTeams(String userId) {
        Result result = new Result();

        //判断userId是否存在
        if (!userIsExist(userId)) {
            result.setSuccess(false);
            result.setErrMsg("用户未找到");
            return result;
        }

        //查询TeamModel
        List<TeamModel> resultTeams = new ArrayList<>();

        List<UserTeams> userTeams = userTeamsMapper.selectByUserId(userId);

        for (UserTeams userTeam : userTeams) {
            if (userTeam.getIsCreator()) {
                continue;
            }
            TeamModel teamModel = new TeamModel();
            teamModel.setJoinTime(userTeam.getJoinTime());
            Team team = teamMapper.selectByPrimaryKey(userTeam.getTeamId());
            teamModel.setInviteCode(team.getInviteCode());
            teamModel.setMemberNum(team.getMemberNum());
            teamModel.setName(team.getName());
            teamModel.setTeamId(userTeam.getTeamId());
            resultTeams.add(teamModel);
        }
        result.setSuccess(true);
        result.setData(resultTeams);
        return result;
    }


    public boolean userIsExist(String userId) {
        //判断userId是否存在
        LoginUser loginUser = loginUserMapper.selectByPrimaryKey(userId);
        if (loginUser == null) {
            return false;
        }
        return true;
    }
}
